package fileshare.fileprocessing;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import fileshare.network.peerProcess;

public class CutJoinFile {

  private static int MAX_PART = 5000; 

  

public static void seperate(int piecesize)
{
	String filename=peerProcess.filename;
File product=new File(filename);
	log.writelog("file name"+filename+"file size"+product.length());
	try{
		cutFileBin(filename, piecesize);
		
	}catch(Exception e){e.printStackTrace();}
}
public static void combine()
{
	log.writelog("the download is complete");
	String filename=peerProcess.filename;
	try{
		joinFileBin(filename);
	}catch(Exception e){e.printStackTrace();log.getExceptionTrace(e);}
}

  public static void cutFileBin(String fileName, int size) throws IOException {
    InputStream is = new FileInputStream(fileName);
    int index = fileName.lastIndexOf(".");
    String ext = "";
    if (index > 0) {
      ext = fileName.substring(index);
      fileName = fileName.substring(0, index);
    }
    int len;
    int count = 0;
    byte[] cbuf = new byte[size];
    while ((len = is.read(cbuf, 0, size)) != -1) {
      OutputStream os = new FileOutputStream(peerProcess.dirname+"//"+peerProcess.realfilename + "_" + count + ext);
      os.write(cbuf, 0, len);
      os.close();
      count++;
      if (count > MAX_PART) {
        break;
      }
    }
  }

 

 
  public static void joinFileBin(String fileName) throws IOException {
    int index = fileName.lastIndexOf(".");
    String sepit=File.separator;
    String ext = "";
    if (index > 0) {
      ext = fileName.substring(index);
      fileName = fileName.substring(0, index);//
     
    }
    String dir="compltefile"+peerProcess.self_index;
    File fdir=new File(dir);
    if(fdir.exists())
    	fdir.delete();
    else
    	fdir.mkdir();
    log.writelog(dir+"//"+fileName +"_join" + ext);
    
    OutputStream writer = new FileOutputStream(dir+"//"+peerProcess.realfilename +"_join" + ext);
    int len;
    byte[] cbuf = new byte[1024 * 200];
    File file;
    for (int i = 0; i <= Integer.MAX_VALUE; i++) {
      file = new File(peerProcess.dirname+"//"+peerProcess.realfilename + "_" + i + ext);
      if (!file.exists()) {
        break;
      }
      InputStream reader = new FileInputStream(file);
      while ((len = reader.read(cbuf, 0, cbuf.length)) != -1) {
    	 // System.out.println("the cbuf length is"+cbuf.length);
        writer.write(cbuf, 0, len);
        writer.flush();
      }
      reader.close();
    }
    writer.close();
  }
}
